﻿using Dapper;
using Infrastructure.DataBaseConnect;
using Infrastructure.IRepository;
using Model.BusinessModel.InPut;
using Model.BusinessModel.OutPut;
using Model.DomainModel;
using Utility.Enum;

namespace Infrastructure.Repository
{
    /// <summary>
    /// 流程仓储接口实现
    /// </summary>
    public class FlowRepository : Repository<Flow>, IFlowRepository
    {
        /// <summary>
        /// 根据流程名称获取数据
        /// </summary>
        /// <param name="flowName">流程名称</param>
        /// <returns></returns>
        public Flow? GetFlowByFlowName(string flowName)
        {
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            string sql = "  select  * from Flow where FlowName  = @FlowName ";
            return connection.QueryFirstOrDefault<Flow>(sql, new { FlowName = flowName });
        }

        /// <summary>
        /// 根据流程id获取数据
        /// </summary>
        /// <param name="flowId">流程id</param>
        /// <returns></returns>
        public FlowOrFormOutPut? GetFlowByFlowId(string flowId)
        {
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            string sql = @"  select a.FlowId,a.FormId,a.FlowName,a.FlowContent,b.FormJson  from  Flow as a
                            inner join Form as b on a.FormId = b.FormId 
                            where a.FlowId=@FlowId and a.DataState  =@DataState";
            return connection.QueryFirstOrDefault<FlowOrFormOutPut>(sql, new { FlowId = flowId, DataState = (int)DataStateEnum.Enable });
        }

        /// <summary>
        /// 更新数据状态
        /// </summary>
        /// <param name="input">输入模型</param>
        /// <returns></returns>
        public void UpdateFlowDataState(UpdateDataStateInput input)
        {
            string sql = "   update Flow set DataState=@DataState where FlowId in @FlowId  ";
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            connection.Query(sql, new { FlowId = input.Ids, input.DataState });
        }

        /// <summary>
        /// 获取所有流程
        /// </summary>
        /// <returns></returns>
        public List<Flow> GetAllFlow()
        {
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            string sql = "  select  * from Flow  ";
            return connection.Query<Flow>(sql).ToList();
        }


        /// <summary>
        /// 根据表单ID,获取流程
        /// </summary>
        /// <param name="formId">表单id</param>
        /// <returns></returns>
        public List<Flow> GetFlowByFormId(string formId)
        {
            string sql = " select * from Flow where FormId=@FormId ";
            using var connection = DataBaseConnectConfig.GetSqlConnection();
            return connection.Query<Flow>(sql, new { FormId = formId }).ToList();
        }
    }
}
